import 'dart:io';

import 'package:detect/notifier/chat.dart';
import 'package:detect/notifier/detect.dart';
import 'package:detect/notifier/fpga_time.dart';
import 'package:detect/notifier/location.dart';
import 'package:detect/notifier/network_state.dart';
import 'package:detect/notifier/offline_map_download.dart';
import 'package:detect/notifier/radio_control.dart';
import 'package:detect/notifier/radio_target.dart';
import 'package:detect/notifier/state.dart';
import 'package:detect/pages/download_map.dart';
import 'package:detect/pages/home.dart';
import 'package:detect/utils/global.dart';
import 'package:detect/utils/permission_util.dart';
import 'package:detect/widgets/loading_widget.dart';
import 'package:detect/widgets/other/custom_underline_tab_indicator.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_color_plugin/flutter_color_plugin.dart';
import 'package:flutter_localization/flutter_localization.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:provider/provider.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  if (await PermissionUtil.location()) {
    await Global.init();
    runApp(MultiProvider(
      providers: [
        ChangeNotifierProvider<NetworkStateNotifier>.value(value: await NetworkStateNotifier.init()),
        ChangeNotifierProvider<StateNotifier>(create: (ctx) => StateNotifier()),
        ChangeNotifierProvider<FpgaTimeNotifier>(create: (ctx) => FpgaTimeNotifier()),
        ChangeNotifierProvider<ChatNotifier>(create: (ctx) => ChatNotifier()),
        ChangeNotifierProvider<DetectNotifier>(create: (ctx) => DetectNotifier()),
        ChangeNotifierProvider<LocationNotifier>(create: (ctx) => LocationNotifier()),
        ChangeNotifierProvider<OfflineMapDownloadNotifier>(create: (ctx) => OfflineMapDownloadNotifier()),
        ChangeNotifierProvider<RadioControlNotifier>(create: (ctx) => RadioControlNotifier()),
        ChangeNotifierProvider<RadioTargetNotifier>(create: (ctx) => RadioTargetNotifier()),
      ],
      child: const AppBoot(),
    ));
  } else {
    SystemChannels.platform.invokeMethod('SystemNavigator.pop');
    exit(exitCode);
  }
}

class AppBoot extends StatefulWidget {
  const AppBoot({super.key});

  @override
  State<AppBoot> createState() => _AppBootState();
}

class _AppBootState extends State<AppBoot> {
  bool get _hasMap {
    String? city = context.read<LocationNotifier>().city;
    return (city?.isNotEmpty ?? false) && context.read<OfflineMapDownloadNotifier>().hasMap(city!);
  }

  @override
  Widget build(BuildContext context) => MaterialApp(
        navigatorKey: Global.navigatorKey,
        title: "短波频探",
        theme: ThemeData(
          useMaterial3: true,
          hoverColor: Colors.black12,
          splashColor: Colors.black12,
          focusColor: Colors.black12,
          highlightColor: Colors.black12,
          disabledColor: Colors.black26,
          primaryColor: ColorUtil.color("#2CA6E0"),
          scaffoldBackgroundColor: Colors.white,
          indicatorColor: ColorUtil.color("#60D8E1"),
          tabBarTheme: TabBarTheme(
            labelPadding: EdgeInsets.all(Global.ds(15)),
            labelColor: ColorUtil.color("#303133"),
            unselectedLabelColor: ColorUtil.color("#999999"),
            labelStyle: TextStyle(fontSize: Global.ds(14)),
            unselectedLabelStyle: TextStyle(fontSize: Global.ds(14)),
            indicatorSize: TabBarIndicatorSize.label,
            indicator: CustomUnderlineTabIndicator(borderSide: BorderSide(width: Global.ds(3), color: ColorUtil.color("#60D8E1"))),
          ),
          iconTheme: IconThemeData(color: ColorUtil.color("#C0C4CC"), size: Global.ds(20)),
          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          appBarTheme: AppBarTheme(
            centerTitle: true,
            elevation: 0,
            scrolledUnderElevation: 0,
            surfaceTintColor: Colors.transparent,
            backgroundColor: Colors.white,
            foregroundColor: ColorUtil.color("#303133"),
            iconTheme: IconThemeData(size: Global.ds(18)),
            actionsIconTheme: IconThemeData(size: Global.ds(18)),
            titleTextStyle: TextStyle(fontSize: Global.ds(18), fontWeight: FontWeight.bold, color: ColorUtil.color("#303133")),
            systemOverlayStyle: const SystemUiOverlayStyle(
              statusBarColor: Color.fromRGBO(255, 255, 255, 0),
              statusBarBrightness: Brightness.light,
              statusBarIconBrightness: Brightness.dark,
            ),
          ),
          textTheme: TextTheme(
            bodyMedium: TextStyle(fontSize: Global.ds(12), color: ColorUtil.color("#303133")),
            bodySmall: TextStyle(fontSize: Global.ds(12), color: ColorUtil.color("#303133")),
            labelSmall: TextStyle(fontSize: Global.ds(12), color: ColorUtil.color("#303133")),
          ),
          elevatedButtonTheme: ElevatedButtonThemeData(
            style: ButtonStyle(
              tapTargetSize: MaterialTapTargetSize.shrinkWrap,
              elevation: MaterialStatePropertyAll(Global.ds(10)),
              padding: const MaterialStatePropertyAll(EdgeInsets.zero),
              minimumSize: const MaterialStatePropertyAll(Size.zero),
              maximumSize: const MaterialStatePropertyAll(Size.infinite),
              surfaceTintColor: const MaterialStatePropertyAll(Colors.white),
              backgroundColor: const MaterialStatePropertyAll(Colors.white),
              shadowColor: MaterialStatePropertyAll(ColorUtil.color("#337D8A8F")),
              foregroundColor: MaterialStatePropertyAll(ColorUtil.color("#303133")),
              textStyle: MaterialStatePropertyAll(TextStyle(fontSize: Global.ds(14))),
              visualDensity: const VisualDensity(horizontal: VisualDensity.minimumDensity, vertical: VisualDensity.minimumDensity),
              shape: MaterialStatePropertyAll(RoundedRectangleBorder(side: BorderSide.none, borderRadius: BorderRadius.circular(Global.ds(4)))),
              overlayColor: MaterialStateColor.resolveWith((Set<MaterialState> states) {
                if (states.contains(MaterialState.hovered)) {
                  return Colors.black12;
                } else if (states.contains(MaterialState.pressed)) {
                  return Colors.black12;
                } else if (states.contains(MaterialState.focused)) {
                  return Colors.black12;
                } else if (states.contains(MaterialState.disabled)) {
                  return Colors.black26;
                } else {
                  return Colors.white;
                }
              }),
            ),
          ),
          textButtonTheme: TextButtonThemeData(
            style: ButtonStyle(
              tapTargetSize: MaterialTapTargetSize.shrinkWrap,
              elevation: const MaterialStatePropertyAll(0),
              padding: const MaterialStatePropertyAll(EdgeInsets.zero),
              minimumSize: const MaterialStatePropertyAll(Size.zero),
              maximumSize: const MaterialStatePropertyAll(Size.infinite),
              surfaceTintColor: const MaterialStatePropertyAll(Colors.white),
              backgroundColor: const MaterialStatePropertyAll(Colors.white),
              shadowColor: const MaterialStatePropertyAll(Colors.transparent),
              foregroundColor: MaterialStatePropertyAll(ColorUtil.color("#303133")),
              textStyle: MaterialStatePropertyAll(TextStyle(fontSize: Global.ds(14))),
              visualDensity: const VisualDensity(horizontal: VisualDensity.minimumDensity, vertical: VisualDensity.minimumDensity),
              shape: MaterialStatePropertyAll(RoundedRectangleBorder(side: BorderSide.none, borderRadius: BorderRadius.circular(Global.ds(4)))),
              overlayColor: MaterialStateColor.resolveWith((Set<MaterialState> states) {
                if (states.contains(MaterialState.hovered)) {
                  return Colors.black12;
                } else if (states.contains(MaterialState.pressed)) {
                  return Colors.black12;
                } else if (states.contains(MaterialState.focused)) {
                  return Colors.black12;
                } else if (states.contains(MaterialState.disabled)) {
                  return Colors.black26;
                } else {
                  return Colors.white;
                }
              }),
            ),
          ),
          buttonTheme: const ButtonThemeData(
            minWidth: 0,
            padding: EdgeInsets.zero,
            hoverColor: Colors.black12,
            splashColor: Colors.black12,
            focusColor: Colors.black12,
            highlightColor: Colors.black12,
            disabledColor: Colors.black26,
            layoutBehavior: ButtonBarLayoutBehavior.padded,
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
            shape: RoundedRectangleBorder(side: BorderSide.none, borderRadius: BorderRadius.zero),
          ),
          inputDecorationTheme: InputDecorationTheme(
            isDense: true,
            alignLabelWithHint: true,
            constraints: const BoxConstraints(minWidth: 0, minHeight: 0, maxWidth: double.infinity, maxHeight: double.infinity),
            contentPadding: EdgeInsets.symmetric(horizontal: Global.ds(5), vertical: 0),
            hintStyle: TextStyle(color: ColorUtil.color("#C0C4CC"), fontSize: Global.ds(14), height: 1.5),
            labelStyle: TextStyle(color: ColorUtil.color("#303133"), fontSize: Global.ds(14), height: 1.5),
            border: InputBorder.none,
          ),
          listTileTheme: ListTileThemeData(
            dense: true,
            contentPadding: EdgeInsets.symmetric(horizontal: Global.ds(15)),
            horizontalTitleGap: 0,
            minLeadingWidth: 0,
            minVerticalPadding: 0,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
        ),
        supportedLocales: FlutterLocalization.instance.supportedLocales,
        localizationsDelegates: FlutterLocalization.instance.localizationsDelegates,
        builder: FlutterSmartDialog.init(loadingBuilder: (msg) => LoadingWidget(desc: msg)),
        navigatorObservers: [FlutterSmartDialog.observer],
        home: _hasMap ? const Home() : const DownloadMap(),
      );
}
